import React, { Fragment, useEffect, useState } from 'react';
import { LikeOutlined } from '@ant-design/icons';
import classNames from 'classnames';
import { useNavigate, useParams } from 'react-router-dom';
import { message, Spin } from 'antd';
import useRegistration from '@/hooks/useRegistration';
import { Departmentchildren, DepartmentItem } from '@/type/registrationType';
import { fetchHospitalDepartmentAPI } from '@/api/hospitalAPI/registrationAPI';
import './Register.scss';
import { UserInfo } from '@/type/userType';
import { useDispatch, useSelector } from 'react-redux';
import { changeModalOpen } from '@/store/modules/userStore';

const Register = () => {
  // 路由传递过来的params参数 医院的编码
  const { hoscode } = useParams();

  const userInfo: UserInfo = useSelector((state: any) => state.userStore.userInfo);

  const dispatch = useDispatch();

  const navigate = useNavigate();

  // 医院科室列表
  const [departmentList, setDepartmentList] = useState<DepartmentItem[]>();

  // 医院详情
  const { registration: hospitalDetail, loading } = useRegistration(hoscode as string);

  // 当前激活的索引
  const [activeIndex, setActiveIndex] = useState(0);


  /**
   * @description 获取医院科室列表的接口
   * */
  const fetchHospitalDepartment = async (): Promise<void> => {
    try {
      const { data } = await fetchHospitalDepartmentAPI(hoscode as string);
      setDepartmentList(data);
    } catch (error: any) {
      message.error(error.message);
    }
  };


  const changeActive = (index: number) => {
    setActiveIndex(index);
    const allTitleArray = document.querySelectorAll('.currentTitle');
    allTitleArray[index].scrollIntoView({
      behavior: 'smooth',
      block: 'start',
    });
  };

  /**
   *@description 跳转到预约排班页面的回调函数
   * */
  const goToSchedule = (depcode: string) => {
    if (userInfo.token) {
      navigate(`/hospital/schedule/${hoscode}/${depcode}`);
    } else {
      dispatch(changeModalOpen(true));
    }
  };

  const render = () => {
    if (loading) {
      return (
        <Spin spinning={loading}></Spin>
      );
    } else {
      return (
        <>
          <div className="top">
            <h2>{hospitalDetail?.hospital?.hosname}</h2>
            <div className="level-info">
              <LikeOutlined className="level-icon" />
              <span className="level">{hospitalDetail?.hospital?.param?.hostypeString}</span>
            </div>
          </div>
          <div className="content">
            <div className="left">
              <img src={`data:image/jpeg;base64,${hospitalDetail?.hospital.logoData}`} alt="" />
            </div>
            <div className="right">
              <div className="number">
                <div className="rules">挂号规则</div>
                <div className="time">预约周期: 10天 放号时间{hospitalDetail?.bookingRule?.releaseTime}: 停挂时间:{hospitalDetail?.bookingRule?.quitTime}</div>
                <div className="logout">退号时间: 就诊前一工作日15:30前取消</div>
                <div className="address">医院地址: {hospitalDetail?.hospital?.param?.fullAddress}</div>
                <div className="route">医院路线: {hospitalDetail?.hospital?.route}</div>
              </div>
              <div className="hos">
                <div className="rules">医院预约规则</div>
                <ul>
                  {hospitalDetail?.bookingRule.rule.map(item => <li key={item}>{item}</li>)}
                </ul>
              </div>
            </div>
          </div>
          <div className="deparment-box">
            <ul className="leftNav">
              {departmentList?.map((item, index) => <li key={item.depcode} className={classNames(index === activeIndex ? 'active' : '')} onClick={() => changeActive(index)}>{item.depname}</li>)}
            </ul>
            <div className="deparmentInfo">
              <div className="showDeptment">

                {
                  departmentList?.map(item => {
                    return (
                      <div className="dept-item" key={item.depcode}>
                        <i className="iconfont icon-Exclude"></i>
                        <span className="currentTitle">{item.depname}</span>
                        <ul>
                          {
                            item.children.map(children => <li key={children.depcode} onClick={() => goToSchedule(children.depcode)}>{children.depname}</li>)
                          }
                        </ul>
                      </div>
                    );
                  })
                }
              </div>
            </div>
          </div>
        </>
      );
    }
  };
  useEffect(() => {
    fetchHospitalDepartment();
    window.scrollTo(0, 0);
  }, []);


  return (

    <div className="detail">
      {
        render()
      }
    </div>

  );
};

export default Register;
